package com.wnhz.work.yz.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.google.gson.Gson;
import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.base.BaseRVAdapter;
import com.wnhz.work.yz.base.BaseViewHolder;
import com.wnhz.work.yz.bean.UpDateTaskBean;
import com.wnhz.work.yz.bean.AddPersonOneBean;
import com.wnhz.work.yz.bean.AddPersonTeamBean;
import com.wnhz.work.yz.bean.TaskPersonBean;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class AddTaskActivity extends BaseActivity implements View.OnClickListener {
    private EditText task_name, task_msg;
    private TextView task_plan;
    private TextView task_start;
    private TextView task_end;
    private TextView task_boss;
    private TextView task_person;
    private int max_cololr;
    private static final int GETPLANID = 12344;
    private static final int GETMANAGER = 12345;
    private static final int GETPERSON = 12346;
    private RecyclerView manager, person;
    private BaseRVAdapter managerAdapter, personAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_task);
        initData();
        initTitle();
        bindViews();
        initListener();
        if (type != -1) {
            upLoad();
        }
    }

    private int type;
    private String task_id;

    private void initData() {
        type = getIntent().getIntExtra("type", -1);
        task_id = getIntent().getStringExtra("task_id");

    }

    private UpDateTaskBean.InfoEntity update = new UpDateTaskBean.InfoEntity();

    private void setUpdateInfo() {
        List<UpDateTaskBean.InfoEntity.MainUserIdEntity> main_user_id = update.getMain_user_id();
        for (int i = 0; i < main_user_id.size(); i++) {
            TaskPersonBean tpb = new TaskPersonBean();
            tpb.setUser_name(main_user_id.get(i).getRealname());
            tpb.setUser_img(main_user_id.get(i).getUser_img());
            tpb.setUser_id(main_user_id.get(i).getUser_id());
            taskBeen.add(tpb);
        }

        List<UpDateTaskBean.InfoEntity.PartUserIdEntity> part_user_id = update.getPart_user_id();
        for (int i = 0; i < part_user_id.size(); i++) {
            TaskPersonBean tpb = new TaskPersonBean();
            tpb.setUser_name(part_user_id.get(i).getRealname());
            tpb.setUser_img(part_user_id.get(i).getUser_img());
            tpb.setUser_id(part_user_id.get(i).getUser_id());
            taskBeen2.add(tpb);

        }
        task_name.setText(update.getTitle());
        task_msg.setText(update.getContent());
        task_plan.setText(update.getPlanning_name());
        task_start.setText(update.getStart_time());
        task_end.setText(update.getEnd_time());
        planId = update.getPlanning_id();
//        managerAdapter.notifyDataSetChanged();
//        personAdapter.notifyDataSetChanged();
        Log.e("===", "" + taskBeen.size() + "---" + taskBeen2.size());
        setManagerData();
        setData();
    }


    private void upLoad() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("task_id", task_id);
        showDialog();
        XUtil.Post(Url.TASK_EDITTASK, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("----", "onSuccess:= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    if ("1".equals(res)) {
                        Gson gson = new Gson();
                        UpDateTaskBean bean = gson.fromJson(result, UpDateTaskBean.class);
                        update = bean.getInfo();
                    } else {
                        if ("-1".equals(res)) {
                            info = "请重新登录";
                        }
                        MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                setUpdateInfo();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                closeDialog();
            }
        });


    }

    private void setManagerData() {
        managerAdapter = new BaseRVAdapter(this, taskBeen) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_add_person2;
            }

            @Override
            public void onBind(BaseViewHolder holder, final int position) {
                x.image().bind(holder.getImageView(R.id.img_head), taskBeen.get(position).getUser_img());
                holder.setTextView(R.id.text_name, taskBeen.get(position).getUser_name());
                holder.getView(R.id.delete).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        taskBeen.remove(position);
                        notifyDataSetChanged();
                        if (taskBeen.size() <= 0) {
                            manager.setVisibility(View.GONE);
                        }
                    }
                });
            }
        };
        manager.setAdapter(managerAdapter);
    }

    private void setData() {

        personAdapter = new BaseRVAdapter(this, taskBeen2) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_add_person2;
            }

            @Override
            public void onBind(BaseViewHolder holder, final int position) {
                x.image().bind(holder.getImageView(R.id.img_head), taskBeen2.get(position).getUser_img());
                holder.setTextView(R.id.text_name, taskBeen2.get(position).getUser_name());
                holder.getView(R.id.delete).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        taskBeen2.remove(position);
                        notifyDataSetChanged();
                        if (taskBeen2.size() <= 0) {
                            manager.setVisibility(View.GONE);
                        }
                    }
                });
            }
        };
        person.setAdapter(personAdapter);
    }


    private void bindViews() {
        manager = (RecyclerView) findViewById(R.id.manager);
        manager.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));

        person = (RecyclerView) findViewById(R.id.person);
        person.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        //
        max_cololr = getResources().getColor(R.color.main_color);
        task_name = (EditText) findViewById(R.id.task_name);
        task_plan = (TextView) findViewById(R.id.task_plan);
        task_start = (TextView) findViewById(R.id.task_start);
        task_end = (TextView) findViewById(R.id.task_end);
        task_boss = (TextView) findViewById(R.id.task_boss);
        task_person = (TextView) findViewById(R.id.task_person);
        task_msg = (EditText) findViewById(R.id.task_msg);
    }

    private void initListener() {
        task_plan.setOnClickListener(this);
        task_start.setOnClickListener(this);
        task_end.setOnClickListener(this);
        task_boss.setOnClickListener(this);
        task_person.setOnClickListener(this);
    }


    private void initTitle() {
        TextView title = (TextView) findViewById(R.id.view_main_middle_title);

        title.setTextColor(getResources().getColor(R.color.main_color));
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        TextView submit = (TextView) findViewById(R.id.submit);
        submit.setOnClickListener(this);
        submit.setVisibility(View.VISIBLE);

        if (type != -1) {
            title.setText("任务详情");
            submit.setText("修改");
        } else {
            title.setText("新建任务");
            submit.setText("保存");
        }
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    private OptionsPickerView pvOptions;
    private TimePickerView pvTime;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_main_left:
                finish();
                break;
            case R.id.submit:
                if (task_name.getText().toString().equals("")) {
                    MyToast("请输入任务标题");
                    return;
                }
                if (task_plan.getText().toString().equals("")) {
                    MyToast("请选择关联计划");
                    return;
                }
                if (taskBeen.size() == 0) {
                    MyToast("请选择负责人");
                    return;
                }
                if (taskBeen2.size() == 0) {
                    MyToast("请选择参与人");
                    return;
                }
                if (task_start.getText().toString().equals("")) {
                    MyToast("请选择开始时间");
                    return;
                }
                if (task_end.getText().toString().equals("")) {
                    MyToast("请选择完成时间");
                    return;
                }
                upLoadAdd();

                break;
            case R.id.task_plan:
                startActivityForResult(new Intent(this, PlanLinkActivity.class), GETPLANID);
                break;
            case R.id.task_start:
                pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        task_start.setText(getTime(date));
                    }
                })
                        .setType(TimePickerView.Type.YEAR_MONTH_DAY)//默认全部显示
                        .setCancelText("取消")//取消按钮文字
                        .setSubmitText("确定")//确认按钮文字
                        .setContentSize(14)//滚轮文字大小
                        .setTitleSize(16)//标题文字大小
                        .setTitleText("开始时间")//标题文字
                        .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                        .isCyclic(false)//是否循环滚动
                        .setTitleColor(max_cololr)//标题文字颜色
                        .setSubmitColor(max_cololr)//确定按钮文字颜色
                        .setCancelColor(max_cololr)//取消按钮文字颜色
                        .setTitleBgColor(Color.WHITE)//标题背景颜色 Night mode
                        .setBgColor(Color.WHITE)//滚轮背景颜色 Night mode
                        // .setRange(calendar.get(Calendar.YEAR) - 20, calendar.get(Calendar.YEAR) + 20)//默认是1900-2100年
                        //.setDate(new Date())// 默认是系统时间*/
                        .setLabel("年", "月", "日", null, null, null)
                        .build();
                pvTime.show();
                break;
            case R.id.task_end:
                pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        task_end.setText(getTime(date));
                    }
                })
                        .setType(TimePickerView.Type.YEAR_MONTH_DAY)//默认全部显示
                        .setCancelText("取消")//取消按钮文字
                        .setSubmitText("确定")//确认按钮文字
                        .setContentSize(14)//滚轮文字大小
                        .setTitleSize(16)//标题文字大小
                        .setTitleText("结束时间")//标题文字
                        .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                        .isCyclic(false)//是否循环滚动
                        .setTitleColor(max_cololr)//标题文字颜色
                        .setSubmitColor(max_cololr)//确定按钮文字颜色
                        .setCancelColor(max_cololr)//取消按钮文字颜色
                        .setTitleBgColor(Color.WHITE)//标题背景颜色 Night mode
                        .setBgColor(Color.WHITE)//滚轮背景颜色 Night mode
                        // .setRange(calendar.get(Calendar.YEAR) - 20, calendar.get(Calendar.YEAR) + 20)//默认是1900-2100年
                       // .setDate(new Date())// 默认是系统时间*/
                        .setLabel("年", "月", "日", null, null, null)
                        .build();
                pvTime.show();
                break;
            case R.id.task_boss:
                startActivityForResult(new Intent(this, GoToAddPersonActivity.class).putExtra("type", 1), GETMANAGER);
                break;
            case R.id.task_person:
                startActivityForResult(new Intent(this, GoToAddPersonActivity.class).putExtra("type", 2), GETPERSON);
                break;
        }
    }


    private void upLoadAdd() {
        Map<String, Object> map = new HashMap<>();
        //参数token 、task_name,planning_id(计划id),start_time,end_time,content,main_user_id(负责人id)，part_user_id(参与人id,用逗号连接成字符串)，task_id(修改时传)
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("task_name", task_name.getText().toString());
        map.put("planning_id", planId);
        map.put("start_time", task_start.getText().toString());
        map.put("end_time", task_end.getText().toString());
        map.put("content", task_msg.getText().toString());
        StringBuffer main = new StringBuffer("");
        main.append("-");
        for (int i = 0; i < taskBeen.size(); i++) {
            main.append(taskBeen.get(i).getUser_id() + "-");
        }
        map.put("main_user_id", main.toString());
        StringBuffer per = new StringBuffer("");
        per.append("-");
        for (int i = 0; i < taskBeen2.size(); i++) {
            per.append(taskBeen2.get(i).getUser_id() + "-");
        }
        map.put("part_user_id", per.toString());
        //  map.put("task_id", MyApplication.getInstance().getUserBean().getToken());
        if (type != -1) {
            map.put("task_id", task_id);
        }

        showDialog();
        Set keys = map.keySet();
        if (keys != null) {
            Iterator iterator = keys.iterator();
            while (iterator.hasNext()) {
                Object key = iterator.next();
                Object value = map.get(key);
                Log.e("----" + key, ":" + value + "\n");
            }
        }
        XUtil.Post(Url.TASK_ADDOREDITTASK, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("----", "onSuccess:= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    if ("1".equals(res)) {
                        MyToast(info);
                        finish();
                    } else {
                        if ("-1".equals(res)) {
                            info = "请重新登录";
                        }
                        MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                closeDialog();
            }
        });
    }

    private String planId;
    private List<TaskPersonBean> taskBeen = new ArrayList<>();
    private List<TaskPersonBean> taskBeen2 = new ArrayList<>();

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case GETPLANID:
                if (resultCode == RESULT_OK) {
                    planId = data.getStringExtra("planid");
                    task_plan.setText(data.getStringExtra("name") + "");
                }
                break;
            case GETMANAGER:
                if (resultCode == RESULT_OK) {
                    if (data.getIntExtra("type", 0) == 0) {
                        ArrayList<AddPersonTeamBean.InfoEntity.TeamUserEntity> user = (ArrayList<AddPersonTeamBean.InfoEntity.TeamUserEntity>) data.getSerializableExtra("user");
                        for (int i = 0; i < user.size(); i++) {
                            TaskPersonBean bean = new TaskPersonBean();
                            bean.setTelephone(user.get(i).getTelephone());
                            bean.setUser_id(user.get(i).getUser_id());
                            bean.setUser_img(user.get(i).getUser_img());
                            bean.setUser_name(user.get(i).getUser_name());
                            boolean flag = false;
                            for (int k = 0; k < taskBeen.size(); k++) {
                                if (user.get(i).getUser_id().equals(taskBeen.get(k).getUser_id())) {
                                    flag = true;
                                }
                            }
                            if (!flag)
                                taskBeen.add(bean);
                        }
                    } else {
                        ArrayList<AddPersonOneBean.InfoEntity> info = (ArrayList<AddPersonOneBean.InfoEntity>) data.getSerializableExtra("user");
                        for (int i = 0; i < info.size(); i++) {
                            TaskPersonBean bean = new TaskPersonBean();
                            bean.setTelephone(info.get(i).getTelephone());
                            bean.setUser_id(info.get(i).getUser_id());
                            bean.setUser_img(info.get(i).getUser_img());
                            bean.setUser_name(info.get(i).getUser_name());
                            boolean flag = false;
                            for (int k = 0; k < taskBeen.size(); k++) {
                                if (info.get(i).getUser_id().equals(taskBeen.get(k).getUser_id())) {
                                    flag = true;
                                }
                            }
                            if (!flag)
                                taskBeen.add(bean);
                        }
                    }
                    setManagerData();
                }

                break;
            case GETPERSON:
                if (resultCode == RESULT_OK) {
                    if (data.getIntExtra("type", 0) == 0) {
                        ArrayList<AddPersonTeamBean.InfoEntity.TeamUserEntity> user = (ArrayList<AddPersonTeamBean.InfoEntity.TeamUserEntity>) data.getSerializableExtra("user");
                        for (int i = 0; i < user.size(); i++) {
                            TaskPersonBean bean = new TaskPersonBean();
                            bean.setTelephone(user.get(i).getTelephone());
                            bean.setUser_id(user.get(i).getUser_id());
                            bean.setUser_img(user.get(i).getUser_img());
                            bean.setUser_name(user.get(i).getUser_name());
                            boolean flag = false;
                            for (int k = 0; k < taskBeen2.size(); k++) {
                                if (user.get(i).getUser_id().equals(taskBeen2.get(k).getUser_id())) {
                                    flag = true;
                                }
                            }
                            if (!flag)
                                taskBeen2.add(bean);
                        }
                    } else {
                        ArrayList<AddPersonOneBean.InfoEntity> info = (ArrayList<AddPersonOneBean.InfoEntity>) data.getSerializableExtra("user");
                        for (int i = 0; i < info.size(); i++) {
                            TaskPersonBean bean = new TaskPersonBean();
                            bean.setTelephone(info.get(i).getTelephone());
                            bean.setUser_id(info.get(i).getUser_id());
                            bean.setUser_img(info.get(i).getUser_img());
                            bean.setUser_name(info.get(i).getUser_name());
                            boolean flag = false;
                            for (int k = 0; k < taskBeen2.size(); k++) {
                                if (info.get(i).getUser_id().equals(taskBeen2.get(k).getUser_id())) {
                                    flag = true;
                                }
                            }
                            if (!flag)
                                taskBeen2.add(bean);
                        }
                    }
                    setData();
                }


                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
